<template>
    <Transition name="modal">
        <div class="sg-form-popup-box" v-if="visible">
            <div class="sg-form-popup-wrap">
                <div class="sg-form-popup-header">
                    <div class="form-title">{{ title }}</div>
                    <i-ep-close class="ep-close-btn" @click="clickButtonHandle({ optionName: 'close' })"></i-ep-close>
                </div>
                <div class="sg-form-popup-content">
                    <Form v-model:value="value" :formList="formList" ref="formRef"></Form>
                </div>
                <sg-button :btnList="btnList" @click-button="clickButtonHandle"></sg-button>
            </div>
        </div>
    </Transition>
</template>

<script lang="ts" setup name="SGForm">
import type { PropType } from 'vue';
import type { IButton } from '@/types/button';
import type { IComponentInfoType } from '@/types/component';
import Form from './form.vue';
const { visible, formValue, title, btnList, formList } = defineProps({
    visible: {
        type: Boolean,
        default: false
    },

    formValue: {
        type: Object,
        default: () => {}
    },

    title: {
        type: String,
        default: '新增'
    },

    btnList: {
        type: Array as PropType<IButton[]>,
        default: () => [
            {
                label: '取消',
                optionName: 'close'
            },
            {
                type: 'primary',
                label: '保存',
                optionName: 'confirm'
            }
        ]
    },
    formList: {
        type: Array as PropType<IComponentInfoType[]>,
        default: () => [],
        required: true
    }
});

type DynamicEmits = {
    (event: string, payload: any): void;
};

const emit = defineEmits<DynamicEmits>();

const formRef = ref();

const value = computed({
    get() {
        return formValue;
    },
    set(val) {
        emit('update:formValue', val);
    }
});
const clickButtonHandle = (item: IButton) => {
    const { optionName } = item;
    if (optionName === 'confirm') {
        const flag = formRef.value.validateFormHandle();
        if (flag) emit(optionName, optionName);
    } else if (optionName === 'close') {
        emit('update:visible', false);
        emit('update:formValue', {});
    }
};
</script>

<style lang="scss" scoped>
.modal-enter-from {
    opacity: 0;
}

.modal-leave-to {
    opacity: 0;
}

.modal-enter-from .sg-form-popup-wrap,
.modal-leave-to .sg-form-popup-wrap {
    transform: scale(1.1);
    transform: scale(1.1);
}
</style>
